/**
 * @file keyboard.c
 *
 * @brief: 
 * @author shengda.huang
 * @email <shengda.huang@broadlink.com.>
 * @version V1.0
 * @date 2021-05-09
 */
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>

/**
 * @brief
 * 
 * @param  None
 * @return  None
 *   @retval None
 */




#define TCP_SERVER_PORT 11223




int GetCtrl(void)
{
    int ret;
    char ch;

    system("stty raw");
    ch = getchar();
    system("stty cooked");

    if (ch == 0x3) {
        return CTRL_EXIT;
    }

    if (ch == '[') {
        system("stty raw");
        ch = getchar();
        system("stty cooked");
    }/* else {
        app_log("rx %c 0x%x", ch, ch);
    }*/

    switch (ch) {
        case 'w':
        ret = CTRL_CAR_FORWARD;
        break;

        case 's':
        ret = CTRL_CAR_BACKWARD;
        break;

        case 'a':
        ret = CTRL_CAR_LEFT;
        break;

        case 'd':
        ret = CTRL_CAR_RIGHT;
        break;

        case 'A':
        ret = CTRL_CAMERA_UP;
        break;

        case 'B':
        ret = CTRL_CAMERA_DOWN;
        break;

        case 'C':
        ret = CTRL_CAMERA_LEFT;
        break;

        case 'D':
        ret = CTRL_CAMERA_RIGHT;
        break;

        default:
        ret = CTRL_INVALID;
        break;
    }

    return ret;
}

void handler(int sockfd)
{
    int tx_bytes, cmd;

    while (1) {
        cmd = GetCtrl();

        if (cmd == CTRL_EXIT) {
            break;
        } else if (cmd == CTRL_INVALID) {
            continue;
        }

        // 发送消息给服务器端
        if ((tx_bytes = send(sockfd, "hello", 5, 0)) < 0) {
            app_log_err("send failed!");
            return;
        }
    }
}

void enter(void)
{
    int sockfd;
    struct sockaddr_in serv_addr;//需要连接的服务器地址信息

    // 1.创建socket
    // AF_INET 表示IPV4
    // SOCK_STREAM 表示TCP
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        app_log_err("create socket failed!");
        return;
    }

    // 填充服务器地址信息
    serv_addr.sin_family = AF_INET; // 网络层的IP协议: IPV4
    serv_addr.sin_port   = htons(TCP_SERVER_PORT); // 传输层的端口号
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 网络层的IP地址: 实际的服务器IP地址
    bzero(&(serv_addr.sin_zero), 8); // 保留的8字节置零

    // 2.发起对服务器的连接信息
    // 三次握手,需要将sockaddr_in类型的数据结构强制转换为sockaddr
    if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < 0) {
        app_log_err("connect failed!");
    } else {
        app_log("connect successful!");
        // 3. block in here
        handler(sockfd);
    }

    //4.关闭
    close(sockfd);
    app_log("socket closed!");
}

/* End of file */



